import {batchCreate, deleteById, list} from '@/services/data-media-pair-api';
import {findByPipelineId} from '@/services/channel-api';
import {PlusOutlined} from '@ant-design/icons';
import {
  ActionType,
  ProCard,
  ProColumns,
  ProDescriptions,
  ProDescriptionsItemProps,
  ProTable
} from '@ant-design/pro-components';
import {Button, Drawer, message, Modal, Space} from 'antd';
import React, {useEffect, useRef, useState} from 'react';
import CreateOrUpdateForm from './components/CreateOrUpdateForm';
import BatchCreateForm from "@/pages/DataMediaPair/MediaPair/components/BatchCreateForm";
import moment from "moment";


const handleBatchAdd = async (fields?: API.BatchDataMediaPair) => {
  const hide = message.loading('正在添加');
  try {
    const res = await batchCreate(fields?.pipelineId, fields?.values)
    hide();
    if (res) {
      message.success('添加成功');
      return true;
    }
    return false;
  } catch (error) {
    hide();
    return false;
  }
};



export type MediaPairProps = {
  pipelineId?: number;
  channelId?: number;
  key?: string;
}

const MediaPair: React.FC<MediaPairProps> = (props) => {

  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [createOrUpdateModalOpen, handleCreateOrUpdateModalOpen] = useState<boolean>(false);
  const [batchCreateOpen, handleBatchCreateOpen] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const [isCreate, handleIsCreate] = useState<boolean>(true);
  const [channel, setChannel] = useState<API.Channel>();
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.DataMediaPair>();

  const pipelineId = props?.pipelineId;
  const channelId = props?.channelId;

  useEffect(() => {
    if (pipelineId){
      findByPipelineId(pipelineId)
        .then(res => setChannel(res.data))
    }
  }, [pipelineId])

  /**
   *  Delete node
   * @zh-CN 删除节点
   *
   * @param selectedRows
   */
  const handleRemove = async (selectedRows: API.DataMediaPair) => {
    const hide = message.loading('正在删除....');
    if (!selectedRows) return true;
    try {
      const res = await deleteById(selectedRows.id);
      hide();
      if (res) {
        message.success('删除成功');
        actionRef.current?.reload();
        return true;
      }
      return false;
    } catch (error) {
      hide();
      return false;
    }
  };
  const commonColumns: ProColumns<API.DataMediaPair>[] = [
    {
      title: '序号',
      dataIndex: 'id',
      hideInSearch: true,
    },
    {
      title: '源表',
      renderText: (_, record) => record?.source?.namespace + '.' + record?.source?.name,
      hideInSearch: true,
    },
    {
      title: '目标表',
      dataIndex: ['type'],
      renderText: (_, record) => record?.target?.namespace + '.' + record?.target?.name,
      hideInSearch: true,
    },
    {
      title: '权重',
      dataIndex: ['pushWeight'],
      hideInSearch: true,
    },
    {
      title: '最后同步时间',
      dataIndex: ['tableStat', 'gmtModified'],
      renderText: (d) => (d? moment(d).format('YYYY-MM-DD HH:mm:ss'): '-'),
      hideInSearch:true,
    }
  ]

  const descriptionPairColumns:ProColumns<API.ColumnPair>[] = [
    {
      title:'源字段' ,
      dataIndex:['sourceColumn','name']
    },
    {
      title:'目标字段' ,
      dataIndex:['targetColumn','name']
    },
  ];

  const descriptionColumns: ProColumns<API.DataMediaPair>[] = [
    ...commonColumns,
    {
      title: 'FileSize',
      dataIndex: ['tableStat', 'fileSize'],
      hideInSearch: true,
    },
    {
      title: 'FileCount',
      dataIndex: ['tableStat', 'fileCount'],
      hideInSearch: true,
    },
    {
      title: 'DeleteCount',
      dataIndex: ['tableStat', 'deleteCount'],
      hideInSearch: true,
    },
    {
      title: 'UpdateCount',
      dataIndex: ['tableStat', 'updateCount'],
      hideInSearch: true,
    },
    {
      title: 'InsertCount',
      dataIndex: ['tableStat', 'insertCount'],
      hideInSearch: true,
    },
    {
      title:'列映射',
      render:(_,record) => {
        if (!(record?.columnPairs)){
          return '-';
        }
        return (
          <ProTable<API.ColumnPair, API.PageParams>
            rowKey="key"
            defaultSize={'middle'}
            search={false}
            pagination={false}
            toolBarRender={false}
            dataSource={record?.columnPairs || []}
            columns={descriptionPairColumns}
          />)
      }
    }
  ];

  const columns: ProColumns<API.DataMediaPair>[] = [
    ...commonColumns,
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => {
        return (
          <Space>
            <a
              key="detail"
              onClick={() => {
                setCurrentRow(record);
                setShowDetail(true);
              }}
            >
              查看
            </a>

            {channel?.status === 'STOP' && (<>
                <a
                  key="edit"
                  onClick={() => {
                    handleCreateOrUpdateModalOpen(true);
                    handleIsCreate(false);
                    setCurrentRow(record);
                  }}
                >
                  编辑
                </a>
                <a
                  type='button'
                  key="delete"
                  onClick={() => {
                    Modal.confirm({title: '确实删除?', onOk: () => handleRemove(record)});
                  }}
                >删除
                </a>
              </>
            )}
          </Space>
        )
      }

    }
  ];

  return (
    <ProCard>
      <ProTable<API.DataMediaPairDTO, API.PipelinePageRequest>
        actionRef={actionRef}
        rowKey="key"
        pagination={false}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              setCurrentRow(undefined);
              handleIsCreate(true);
              handleCreateOrUpdateModalOpen(true);
            }}
          >
            <PlusOutlined/> 新建
          </Button>,
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              setCurrentRow(undefined);
              handleCreateOrUpdateModalOpen(false);
              handleBatchCreateOpen(true);
            }}
          >
            <PlusOutlined/> 批量新增
          </Button>,
        ]}
        request={list}
        params={{pipelineId:pipelineId}}
        columns={columns}
      />
      <CreateOrUpdateForm
        pipelineId={pipelineId}
        channelId={channelId}
        onFinish={async () => {
          handleCreateOrUpdateModalOpen(false);
          setCurrentRow(undefined);
          await actionRef?.current?.reload();
        }}
        title={isCreate ? '新建' : '编辑'}
        onCancel={() => {
          handleCreateOrUpdateModalOpen(false);
          if (!showDetail) {
            setCurrentRow(undefined);
          }
        }}
        updateModalOpen={createOrUpdateModalOpen}
        values={isCreate? undefined : currentRow}
      />

      <BatchCreateForm
        onSubmit={async (value) => {
          let success = await handleBatchAdd(value);
          if (success) {
            handleBatchCreateOpen(false);
            setCurrentRow(undefined);
            await actionRef?.current?.reload();
          }
        }}
        title={'新建'}
        onCancel={() => {
          handleBatchCreateOpen(false);
          if (!showDetail) {
            setCurrentRow(undefined);
          }
        }}
        updateModalOpen={batchCreateOpen}
        values={currentRow?.pipelineId}
      />

      <Drawer
        width={500}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.id && (
          <ProDescriptions<API.DataMediaPair>
            column={2}
            dataSource={currentRow}
            columns={descriptionColumns as ProDescriptionsItemProps<API.DataMediaPair>[]}
          />
        )}
      </Drawer>
    </ProCard>
  );
};

export default MediaPair;
